<?php

namespace app\admin\controller;

use app\api\model\ConfigAlipay;
use app\api\model\ConfigPersonal;
use app\api\model\Labels;
use app\api\model\Privatechat;
use app\api\model\LabelsUser;
use think\Db;
use think\Session;
use app\api\model\Task;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Memberbak extends Common
{
    public function adminlog()
    {
        $where = [];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $where['city'] = ['like', $admin['city'] . '%'];
        }

        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('admin_logs')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //会员管理
    public function index()
    {
        // 处理账号到期解冻
        Db::name('user')
            ->where(['is_banned' => 1, 'banned_end_time' => ['elt', date('Y-m-d H:i:s')]])
            ->update(['is_banned' => 0, 'banned_end_time' => null]);

        //$where = ['proxy' => ['neq', 1]];
        $where = ['id' => ['gt', 0]];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $where['city'] = ['like', $admin['city'] . '%'];
        }

        $type = input('type');
        if ($type == 1) {
            $where['vip_end_datetime'] = ['egt', date('Y-m-d H:i:s')];
        } else if ($type == 2) {
            $where['is_identity_authentication'] = '2';
            $where['sex'] = "女";
        } else if ($type == 3) {
            $where['register_datetime'] = ['egt', date('Y-m-d')];
        }

        $xuni = input('xuni/d');
        if ($xuni) {
            $xuni_table = $xuni - 1;
            $where['role'] = $xuni_table;
        }

        $sex = input('sex');
        if ($sex) {
            $where['sex'] = $sex;
        }

        $is_online = input('is_online');
        if ($is_online) {
            $where['is_online'] = $is_online;
        }
    
        $recommend = input('recommend');
        if ($recommend) {
            $where['is_recommend'] = $recommend;
        }

        $is_contact = input('is_contact');
        if ($is_contact !== null) {
            $where['is_contact'] = $is_contact;
        }

        $reward = input('reward');
        if ($reward) {
            $order = 'shouyi_xuni desc, shouyi desc';
        } else {
            $order = 'sort desc, id desc';
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if (in_array($search_type, ['id', 'yqr'])) {
                $where[$search_type] = $search_name;
            } else if ($search_type == 'cluster') {
                $ids = Db::name('cluster_user')->where(['cluster_id' => $search_name])->column('user_id');

                if ($ids) {
                    $where['id'] = ['in', $ids];
                } else {
                    $where['id'] = 0;
                }
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $proxy = input('proxy');
        if ($proxy) {

            $channel = input('channel');
            switch ($channel) {
                case 1:
                    $where['yqr'] = $proxy;
                    break;
                case 2:
                    $users = Db::name("user")->field('id, register_datetime')->where(["yqr" => $proxy])->select();
                    if ($users) {
                        $ids = array_column($users, 'id');
                        $uids = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->group('user_id')->column('user_id');
                        if ($uids) {
                            $where['id'] = ['in', $uids];
                        } else {
                            $where['id'] = 0;
                        }
                    } else {
                        $where['id'] = 0;
                    }
                    break;
                case 3:
                    $where['yqr'] = $proxy;
                    $where['register_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime(date('Ymd')))];
                    break;
                case 4:
                    $users = Db::name("user")->field('id, register_datetime')->where(["yqr" => $proxy])->select();
                    if ($users) {
                        $ids = array_column($users, 'id');
                        $uids = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->whereTime('update_time', 'd')->order('id desc')->group('user_id')->column('user_id');
                    } else {
                        $uids = [];
                    }
                    if ($uids) {
                        $where['id'] = ['in', $uids];
                    } else {
                        $where['id'] = 0;
                    }
                    break;
            }
        }

        $date = input('date');
        if ($date) {
            $where['register_datetime'] = ['like', '%' . $date . '%'];
        }

        $data = Db::name('user')->where($where)->order($order)->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $count = Db::name('user')->where($where)->count();
        $sum = Db::name('user')->count();

        $vip = Db::name('grade_noble')->order('sort desc, id asc')->column('grade, id, name');
        $this->assign('vip', $vip);

        $car = Db::name('car')->where(['is_hidden' => 0])->column('id, name, description');
        $this->assign('car', $car);

        $this->assign('type', $type);
        $this->assign('xuni', $xuni);
        $this->assign('sex', $sex);
        $this->assign('is_online', $is_online);
        $this->assign('recommend', $recommend);
        $this->assign('is_contact', $is_contact);
        $this->assign('reward', $reward);
        $this->assign('count', $count);
        $this->assign('sum', $sum);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    // 添加会员
    public function add()
    {
        $id = input('id');
        $xuni = input('xuni/d');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!isset($post['longitude']) || !$post['longitude']) {
                unset($post['longitude']);
            }

            if (!isset($post['latitude']) || !$post['latitude']) {
                unset($post['latitude']);
            }

            if (isset($post['fencheng_user']) && $post['fencheng_user']) {
                $post['fencheng_user'] = $post['fencheng_user'] / 100;
            }

            if ($xuni) {
                $userNum = $post['userNum'];
                unset($post['userNum']);
            }

            if ($post['sex'] == '男') {
                if (isset($post['dy_conditions_woman'])) {
                    unset($post['dy_conditions_woman']);
                }

                if (isset($post['dy_conditions_man'])) {
                    $post['dy_conditions'] = implode(',',$post['dy_conditions_man']);
                    unset($post['dy_conditions_man']);
                } else {
                    $post['dy_conditions'] = '';
                }
            } else {
                if (isset($post['dy_conditions_man'])) {
                    unset($post['dy_conditions_man']);
                }

                if (isset($post['dy_conditions_woman'])) {
                    $post['dy_conditions'] = implode(',',$post['dy_conditions_woman']);
                    unset($post['dy_conditions_woman']);
                } else {
                    $post['dy_conditions'] = '';
                }
            }

            if (isset($post['dy_program'])) {
                $post['dy_program'] = implode(',',$post['dy_program']);
            } else {
                $post['dy_program'] = '';
            }

            if (isset($post['good_label'])) {
                $good_label = implode(',',$post['good_label']);
                unset($post['good_label']);
            } else {
                $good_label = '';
            }

            if (isset($post['interested_label'])) {
                $interested_label = implode(',',$post['interested_label']);
                unset($post['interested_label']);
            } else {
                $interested_label = '';
            }

            $validate = validate('Member');

            if ($validate->check($post)) {

                if (!$id) {
                    if (!$post['password']) {
                        return ['err' => '请填写密码'];
                    }

                    if (!$post['sex']) {
                        return ['err' => '请填写性别'];
                    }

                    if (isset($post['phone']) && $post['phone']) {
                        $res = Db::name('user')->where('phone', $post['phone'])->select();
                        if ($res) {
                            return ['err' => '手机号已存在'];
                        }
                    } else {
                        $post['phone'] = null;
                    }

                    if (!$post['head_portrait'] && !$xuni) {
                        //return ['err' => '请先上传头像'];
                    } else {
                        $post['head_300'] = $post['head_portrait'];
                        $post['head_100'] = $post['head_portrait'];
                    }

                    if ($xuni) {
                        $contain = [];
                        for ($i = 0; $i < $userNum; $i++) {

                            //生成唯一邀请码
                            for ($k = 1; $k < 2; $k++) {
                                $code = code();

                                $test = Db::table('user')->where(['yqm' => $code])->select();
                                if ($test) {
                                    $k--;
                                    break;
                                }
                            }
                            $name = suiji();
                            $post['yqm'] = $code;

                            if (!isset($post['name']) || !$post['name']) {
                                $post['name'] = $name;
                            }
                            if (!isset($post['banned_end_time']) || !$post['banned_end_time']) {
                                $post['banned_end_time'] = null;
                            }

                            if (isset($post['head_portrait'])) {
                                $post['head_100'] = $post['head_300'] = $post['head_portrait'];
                            }

                            $post['role'] = 1;
                            $post['is_online'] = 1;

                            if ($post['sex'] == '男') {
                                $post['attestation'] = 1;
                                $post['is_identity_authentication'] = 2;
                            }

                            $contain[] = $post;
                        }

                        $db = Db::name('user')->insertAll($contain);
                    } else {
                        //生成唯一邀请码
                        for ($i = 2; $i > 1; $i++) {
                            $code = code();

                            $test = Db::table('user')->where('yqm', $code)->select();
                            if (!$test) {
                                $i = 0;
                            }
                        }

                        $post['yqm'] = $code;

                        $db = Db::name('user')->insertGetId($post);

                        ConfigPersonal::createData($db, $post['sex']);
                    }

                    if ($db) {
                        if (isset($good_label)) {
                            Labels::edit($good_label, $db);
                        }

                        if (isset($interested_label)) {
                            Labels::edit($interested_label, $db, 2);
                        }

                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {  //修改数据
                    $userInfo = Db::name('user')->find($id);

                    if ($userInfo['yqr'] && (!isset($post['yqr']) || !$post['yqr'] || $post['yqr'] == '')) {
                        $parentInfo = Db::name('user')->where(['yqm' => $userInfo['yqr']])->find();
                        if ($parentInfo && $parentInfo['proxy'] < 1) {
                            unset($post['yqr']);
                        }
                    }

                    if ($post['is_banned']) {
                        if (!$post['banned_end_time']) return ['err' => '先选择冻结时间'];
                    } else {
                        $post['banned_end_time'] = null;
                    }

                    if (!$post['head_portrait']) {
                        //return ['err' => '请先上传头像'];
                    } else {
                        $post['head_300'] = $post['head_portrait'];
                        $post['head_100'] = $post['head_portrait'];
                    }

                    if (isset($post['password']) && !$post['password']) {
                        unset($post['password']);
                    }

                    if ($post['phone']) {
                        $record = Db::name('user')->where(['phone' => $post['phone']])->find();
                        if ($record) {
                            if ($record['id'] != $id) return ['err' => '手机号已存在'];
                        }
                    }
                    $post['phone'] = $post['phone'] ?: null;


                    $db = Db::name('user')->where('id', $id)->update($post);

                    if ($db !== false) {
                        if (isset($good_label)) {
                            Labels::edit($good_label, $id);
                        }

                        if (isset($interested_label)) {
                            Labels::edit($interested_label, $id, 2);
                        }

                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                $name = Db::name('user')->where('id', $id)->find();
                if ($name) {
                    if ($name['dy_program']) {
                        $name['dy_program'] = explode(',',$name['dy_program']);
                    } else {
                        $name['dy_program'] = [];
                    }

                    if ($name['dy_conditions']) {
                        $name['dy_conditions'] = explode(',',$name['dy_conditions']);
                    } else {
                        $name['dy_conditions'] = [];
                    }

                    $good_label = $interested_label = [];

                    $label = LabelsUser::where(['user_id' => $id])->column('id, types, label_id');

                    foreach ($label as $item) {
                        if ($item['types'] == 1) {
                            $good_label[] = $item['label_id'];
                        } else if ($item['types'] == 2) {
                            $interested_label[] = $item['label_id'];
                        }
                    }
                    $name['good_label'] = $good_label;
                    $name['interested_label'] = $interested_label;

                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }

                $this->assign('id', $id);
            }

            $proxys = Db::name('user')->where(['proxy' => 1])->column('yqm, id, name');
            $this->assign('proxys', $proxys);

            $category = Db::name('dymanic_category')->where(['is_hide' => 0])->order('des asc, id asc')->select();
            $this->assign('category', $category);

            $conditions = Db::name('user_conditions')->where(['hide' => 0])->order('des desc, id asc')->select();
            $conditions_man = [];
            $conditions_woman = [];
            if ($conditions) {
                foreach ($conditions as $k => $v) {
                    if ($v['type'] == 1) {
                        $conditions_man[] = $v;
                    } else {
                        $conditions_woman[] = $v;
                    }
                }
            }
            $this->assign('conditions_man', $conditions_man);
            $this->assign('conditions_woman', $conditions_woman);

            $occupation = Db::name('user_occupation')->where(['hide' => 0])->order('des desc, id asc')->select();
            $this->assign('occupation', $occupation);

            $labels = Db::name('labels')->where(['is_hidden' => 0])->order('sort desc, id asc')->select();
            $this->assign('labels', $labels);

            $this->assign('xuni', $xuni);

            $data = $this->fetch();
        }

        return $data;
    }

    //删除会员
    public function del()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('user')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // 批量删除
    public function delAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if (input('?post.delAll')) {
                $post = $post['delAll'];

                $db = Db::name('user')->where('id', 'in', $post)->delete();

                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => '删除失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    // 快速设置 拒绝 审核 禁止 通过
    public function hide()
    {
        if (request()->isAjax()) {

            $id = input('id') ? input('id') : '0';
            $type = input('type') ? input('type') : '0';
            $text = ['0' => '<font color="#f00">禁止</font>', '1' => '<font color="#1ab394">通过</font>', '2' => '审核', '3' => '<font color="#f00">拒绝</font>'];
            if ($id) {
                $db = Db::name('member')->where('id', $id)->setField('hide', $type);
                if ($db) {
                    $data = [$text[$type]];
                } else {
                    $data = ['删除失败'];
                }
            } else {
                $data = ['GET值错误'];
            }
        } else {
            $data = ['提交错误'];
        }
        return $data;
    }

    // 用户记录
    public function records()
    {
        $money = input('money') ? input('money') : '';
        $type = input('type') ? input('type') : '';
        $data = input('data') ? input('data') : '';
        $where = [];
        if ($type) {
            if ($type == '-1') {
                $where['money'] = 0;
            } else {
                $where['type'] = $type;
            }
        }
        $db = Db::name('member_records')->order('id desc,time desc')->where($where)->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $data = $db->toarray()['data'];
        $type = ['money' => '元', 'score' => '积分', 'jingyan' => '经验值'];
        foreach ($data as $k => $v) {
            if ($v['money']) {
                $data[$k]['text'] = $v['text'] . ' <b id="data1">' . $v['data'] . '</b><b id="data2">' . $v['money'] . '</b> ' . $type[$v['type']];
            }
        }
        $this->assign('data', $data);
        $page = $db->render();
        $this->assign('page', $page);
        $this->assign('type', input('type'));
        return $this->fetch();
    }

    //删除记录  禁用
    public function recordsDel()
    {
        return false;
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('member_records')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //视频认证列表
    public function revideo()
    {
        $map = [];
        $revideo = input('revideo');
        if ($revideo) {
            $map['is_identity_authentication'] = $revideo;
        } else {
            $map['is_identity_authentication'] = ['neq', '0'];
        }
        $this->assign('revideo', $revideo);


        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $map[$search_type] = ['like', '%' . $search_name . '%'];
        }


        // $data = Db::table('user')
        //  ->alias('t1')
        //  ->field('t1.*,t2.video as videourl')
        //  ->join('authentication_img t2','t2.user_id = t1.id')
        //  ->where($map)
        //  ->order('t1.revideotime desc,t1.id desc')
        //  ->paginate(_getCachePages(),false,['query'=>request()->param()]);


        $data = Db::name('user')->where($map)->order('revideotime desc,id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //视频认证列表
    public function recar()
    {
        $map = [];
        $recar = input('recar');
        if ($recar) {
            $map['recar'] = $recar;
        } else {
            $map['recar'] = ['neq', '0'];
        }
        $this->assign('recar', $recar);


        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $map[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('user')->where($map)->order('recartime desc,id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //视频认证处理
    public function revideoadd()
    {

        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            $validate = validate('Member');

            if ($validate->check($post)) {
                if (!$id) { //添加数据
                    if (!$post['uid']) {
                        return ['err' => '用户ID不能为空'];
                    }
                    $res = Db::name('preach')->where('uid', $post['uid'])->where('state', 'in', '0,1')->select();
                    if ($res) {
                        return ['err' => '用户已申请，待审核或已通过'];
                    }

                    $db = Db::name('preach')->insert($post);
                    if ($db) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {  //修改数据
                    /*$post['revideotime'] = date('Y-m-d H:i:s');*/

                    if ($post['is_identity_authentication'] == 2) {
                        $post['attestation'] = 1;
                    } else {
                        $post['attestation'] = 0;
                    }

                    $db = Db::name('user')->where('id', $id)->update($post);
                    if ($db) {
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                $name = Db::name('user')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //车辆认证处理
    public function recaradd()
    {

        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            $validate = validate('Member');

            if ($validate->check($post)) {
                if (!$id) { //添加数据
                    if (!$post['uid']) {
                        return ['err' => '用户ID不能为空'];
                    }
                    $res = Db::name('preach')->where('uid', $post['uid'])->where('state', 'in', '0,1')->select();
                    if ($res) {
                        return ['err' => '用户已申请，待审核或已通过'];
                    }

                    $db = Db::name('preach')->insert($post);
                    if ($db) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {  //修改数据
                    $post['recartime'] = date('Y-m-d H:i:s');

                    $db = Db::name('user')->where('id', $id)->update($post);
                    if ($db) {
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                $name = Db::name('user')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //认证视频预览
    public function watch()
    {
        if (!input('?id')) {
            $this->error("参数错误");
        }
        $id = input('id/d');
        $name = Db::name('authentication_img')->where(['user_id' => $id])->find();
        $this->assign('name', $name);
        return $this->fetch();
    }

    //vip档位
    public function vipstyle()
    {
        $map = [];
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $map[$search_type] = ['like', '%' . $search_name . '%'];
        } else {
            $map = '';
        }

        $data = Db::name('vip_style')->where($map)->order('sort desc, id asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //添加修改vip
    public function vipdwadd()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (($post['times'] == 'day' && $post['keep'] >= 30) ||
                ($post['times'] == 'month' && $post['keep'] >= 12)) {
                return ['err' => '有效期数值超出范围'];
            }

            if (!$id) {
                $db = Db::name('vip_style')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {//修改数据

                $db = Db::name('vip_style')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('vip_style')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除vip档位
    public function vipdel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('vip_style')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //vip购买订单
    public function viporder()
    {
        $map = [];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $type = input('type');

        if ($type == 1) {
            $map['t1.type'] = '0';
        } else if ($type == 2) {
            $map['t1.type'] = '1';
        } else if ($type == 3) {
            $map['t1.pay'] = '1';
        } else if ($type == 4) {
            $map['t1.pay'] = '2';
        } else if ($type == 5) {
            $map['t1.pay'] = '3';
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $date = input('date');
        if ($date) {
            $map['t1.time'] = ['like', '%' . $date . '%'];
        }

        $map['t1.desc'] = ['not like', '%后台添加'];

        $data = Db::table('vip_order t1')
            ->field('t1.*,t2.name, t3.name, t3.description')
            ->join('user t2', 't2.id = t1.user_id')
            ->join('vip_style t3', 't1.sid = t3.id')
            ->where($map)
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $map['t1.type'] = 1;

        $sum = Db::table('vip_order t1')->join('user t2', 't2.id = t1.user_id')->where($map)->sum('price');

        $this->assign('sum', $sum);
        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //删除vip购买订单
    public function orderdel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('vip_order')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //提现管理
    public function tixian()
    {
        $map = [];
        $daili = [];    //城市代理管理员查看筛选

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
            $daili['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $daili['state'] = '1';
        $month = Db::name('withdraw t1')->join('user t2', 't2.id = t1.userid')->where($daili)->whereTime('create_time', 'm')->sum('t1.money');

        $type = input('type');
        if ($type == 1) {
            $map['t1.paymethod'] = '0';
        } else if ($type == 2) {
            $map['t1.paymethod'] = '1';
        } else if ($type == 3) {
            $map['t1.state'] = '0';
        } else if ($type == 4) {
            $map['t1.state'] = '1';
        } else if ($type == 5) {
            $map['t1.state'] = '2';
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $date = input('date');
        if ($date) {
            $start = strtotime($date);
            $end = $start + 86399;
            $map['t1.create_time'] = ['between', [$start, $end]];
        }

        $data = Db::name('withdraw t1')
            ->field('t1.*,t2.name')
            ->join('user t2', 't2.id = t1.userid')
            ->where($map)
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);


        $sum = Db::table('withdraw t1')->join('user t2', 't2.id = t1.userid')->where($map)->sum('money');
        $this->assign('sum', $sum);
        $this->assign('month', $month);
        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function tixianadd()
    {
        $id = input("id/d");

        $state = input("state");
        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) {

                $db = Db::name('withdraw')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $updates = ['state' => $state, 'update_time' => time()];

                    $withdraw = Db::name('withdraw')->find($id);

                    if ($state == 2) {
                        $content = '提现申请驳回';

                        $reason = input('reason');
                        if ($reason) {
                            $updates['reason'] = input('reason');

                            $content .= '。理由：' .$reason;
                        }
                        //返还
                        Db::name('user')->where('id', $withdraw['userid'])->setInc('score', ($withdraw['price'] + $withdraw['shouxu']));

                        Db::name('yaoqing_records')->insert(['uid' => $withdraw['userid'], 'content' => $content, 'money' => $withdraw['price'] + $withdraw['shouxu'], 'time' => time(), 'type' => 1]);
                        /*$data = [
                            'user_id' => $user['userid'],
                            'content' => '提现失败返还',
                            'price' => $user['money'],
                            'time' => time()
                        ];
                        $cmoney = Db::name('volley_desc')->insert($data);*/
                    } else {
                        $datas = json_decode($withdraw['data'], true);

                        if (!isset($datas['name']) || !$datas['name']) {
                            return ['err' => '未填写提现到款账户姓名'];
                        }

                        if (!isset($datas['account']) || !$datas['account']) {
                            return ['err' => '未填写提现到款账户'];
                        }

                        $configAlipay = ConfigAlipay::get(['types' => 2, 'is_select' => 1]);

                        if (!$configAlipay || !$configAlipay['appid'] || !$configAlipay['private_key'] || !$configAlipay['public_key']) {
                            //return ['err' => '请先配置支付宝转账参数'];
                        } else {
                            if ($withdraw['money'] < 1) {
                                return ['err' => '转账金额不能低于1元'];
                            }

                            $response = action('api/Alipay/transfer', [
                                'out_biz_no' => $withdraw['id'] . uniqid(),
                                'payee_account' => $datas['account'],
                                'amount' => $withdraw['money'],
                                'payee_real_name' => $datas['name'],
                            ]);

                            if (isset($response['code'])) {
                                if ($response['code'] == 10000) {
                                    $datas['order_id'] = $response['order_id'];
                                    $datas['out_biz_no'] = $response['out_biz_no'];
                                    $datas['pay_date'] = $response['pay_date'];

                                    $updates['data'] = json_encode($datas, JSON_UNESCAPED_UNICODE);
                                } else {
                                    return ['err' => $response['msg']];
                                }
                            } else {
                                if (stripos($response, 'PAYER_BALANCE_NOT_ENOUGH')) {
                                    return ['err' => '付款方余额不足'];
                                } else if (stripos($response, 'PAYEE_NOT_EXIST')) {
                                    return ['err' => '收款方账号不存在'];
                                } else if (stripos($response, 'PAYEE_USER_INFO_ERROR')) {
                                    return ['err' => '收款方账号与姓名不匹配'];
                                } else {
                                    return ['err' => $response];
                                }
                            }
                        }

                        Db::name('platform_balance')->insert(['types' => 1, 'money' => $withdraw['money'], 'content' => '用户(ID:' . $withdraw['userid'] . ')提现', 'create_time' => time()]);
                    }

                    $res= Db::name('withdraw')->where('id', $id)->update($updates);

                $data = ['ret' => '修改成功'];
            }
        } else {
            if ($id) {
                $name = Db::name('withdraw')->find($id);
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除提现记录
    public function tixiandel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('withdraw')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //充值管理
    public function topup()
    {
        $state = input('state');

        $map = ['t1.type' => ['neq', 3], 'state' => ['neq', 2]];
        $daili = [];    //城市代理管理员查看筛选

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
            $daili['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $daili['state'] = '1';
        //$sum = db('topup')->alias('t1')->join('user t2', 't2.id = t1.fk_userid')->where($daili)->sum('t1.price');
        //$month = db('topup')->alias('t1')->join('user t2', 't2.id = t1.fk_userid')->where($daili)->where('addtime', 'like', date('Y-m') . '%')->sum('t1.price');

        if ($state !== null) {
            $map['t1.state'] = $state;
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $map['t1.addtime'] = ['between', [date('Y-m-d H:i:s', strtotime($start)), date('Y-m-d H:i:s', strtotime($end) + 86400)]];
        } else if ($start && !$end) {
            $map['t1.addtime'] = ['egt', date('Y-m-d H:i:s', strtotime($start))];
        } else if (!$start && $end) {
            $map['t1.addtime'] = ['lt', date('Y-m-d H:i:s', strtotime($start) + 86400)];
        }

        $data = Db::table('topup')
            ->alias('t1')
            ->field('t1.*,t2.name')
            ->join('user t2', 't2.id = t1.fk_userid', 'LEFT')
            ->where($map)
            ->order('t1.addtime desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $sum = Db::table('topup t1')->join('user t2', 't2.id = t1.fk_userid', 'LEFT')->where($map)->sum('t1.price');

        $month = Db::table('topup t1')->join('user t2', 't2.id = t1.fk_userid', 'LEFT')->where($map)->whereTime('t1.addtime', 'm')->sum('t1.price');

        $this->assign('sum', $sum);
        $this->assign('month', $month);
        $this->assign('state', $state);

        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);


        return $this->fetch();
    }

    //删除充值记录
    public function topupdel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('topup')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //特权分组
    public function tequan()
    {
        $data = Db::name('tequan_type')->where(['id' => 1])->order('des desc,id asc')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    // 添加分组
    public function typeadd()
    {
        $id = input("id");
        if (request()->isAjax()) {

            $post = input('post.');
            $time = time();
            $post['update_time'] = $time; //更新时间
            if (!$id) {   // 添加数据
                $titledb = Db::name('tequan_type')->where('title', $post['title'])->find();
                if ($titledb) {
                    return ['err' => '分组标题已存在'];
                }
                $post['create_time'] = $time; // 添加时间
                $db = Db::name('tequan_type')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {      //修改数据
                $db = Db::name('tequan_type')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }

        } else {
            if ($id) {
                $name = Db::name('tequan_type')->where('id', $id)->find();
                //var_dump($name);die();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    // 特权次数列表
    public function lists()
    {
        $tid = input('tid');

        if ($tid == 1) {
            $data = Db::name('vip_config')->where('id', 1)->select();
        } else if ($tid == 2) {
            $data = Db::name('num_config')->order('id desc')->select();
        } else if ($tid == 3) {
            $data = Db::name('vip_config')->where('id', 2)->select();
        }

        $this->assign('tid', $tid);
        $this->assign('data', $data);

        return $this->fetch('list');
    }

    // 特权添加、修改
    public function tequanadd()
    {
        $id = input("id");
        $tid = input("tid");

        $this->assign('tid', input("tid"));
        $slide_type = Db::name('tequan_type')->select();
        $this->assign('tequan_type', $slide_type);

        if (request()->isAjax()) {
            $post = input('post.');
            if ($id) {
                if (in_array($tid, [1,3])) {
                    $arr = [
                        'count' => $post['count'],
                        'time' => date('Y-m-d H:i:s')
                    ];
                    $db = Db::name('vip_config')->where('id', $id)->update($arr);
                } else if ($tid == 2) {
                    $arr = [
                        'name' => $post['name'],
                        'money' => $post['money'],
                        'time' => date('Y-m-d H:i:s')
                    ];
                    $db = Db::name('num_config')->where('id', $id)->update($arr);
                }

                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                if (in_array($tid, [1,3])) {
                    $name = Db::name('vip_config')->find($id);
                } else if ($tid == 2) {
                    $name = Db::name('num_config')->where('id', $id)->find();
                }

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //会员照片管理
    public function image()
    {
        $id = input('id');

        $data = Db::name('user_img')->where('user_id', $id)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //删除照片
    public function imgdel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            $uid = Db::table('user_img')->where('id', $id)->value('user_id');

            if ($id) {
                $db = Db::name('user_img')->delete($id);
                if ($db) {

                    $context = ['desc' => "图片不合法,已被系统屏蔽"];
                    $arr = [
                        'to_user' => $uid,
                        'context' => json_encode($context, JSON_UNESCAPED_UNICODE),
                        'type' => 2
                    ];
                    Db::table('sys_message')->insert($arr);

                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //照片付费管理
    public function zpfufei()
    {
        $where = [];
        $whereOr = [];

        $type = input('type');
        if ($type == 1) {
            $where['t1.time'] = ['egt', date('Y-m-d H:i:s', strtotime(date('Y-m-d')))];
        }
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            if ($search_type == 'id') {
                $where['t1.' . $search_type] = $search_name;
            } else if ($search_type == 'uid') {
                $where['t1.user_id'] = ['like', '%' . $search_name . '%'];
                $whereOr['t1.to_user'] = ['like', '%' . $search_name . '%'];
            }
        }

        $data = Db::table('packet_img')
            ->alias('t1')
            ->field('t1.*,t2.name,t3.pic')
            ->join('user t2', 't2.id = t1.to_user')
            ->join('user_img t3', 't3.id = t1.img_id')
            ->where($where)
            ->whereOr($whereOr)
            ->order('t1.time desc,t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //相册付费管理
    public function xcfufei()
    {
        $where = [];
        $whereOr = [];

        $type = input('type');
        if ($type == 1) {
            $where['t1.time'] = ['egt', date('Y-m-d H:i:s', strtotime(date('Y-m-d')))];
        }
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $where['t1.user_id'] = ['like', '%' . $search_name . '%'];
            $whereOr['t1.to_user'] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::table('auth_img')
            ->alias('t1')
            ->field('t1.*,t2.name,t2.head_portrait')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)
            ->whereOr($whereOr)
            ->order('t1.time desc,t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //关注管理
    public function attention()
    {
        $where = [];
        $whereOr = [];

        $type = input('type');
        if ($type == 1) {
            $where['t1.addtime'] = ['egt', date('Y-m-d H:i:s', strtotime(date('Y-m-d')))];
        }
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $where['t1.user_id'] = ['like', '%' . $search_name . '%'];
            $whereOr['t1.to_user'] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::table('attention')
            ->alias('t1')
            ->field('t1.*,t2.name,t2.head_portrait')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)
            ->whereOr($whereOr)
            ->order('t1.addtime desc,t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //关注管理
    public function blacklist()
    {
        $where = [];
        $whereOr = [];

        $type = input('type');
        if ($type == 1) {
            $where['t1.addtime'] = ['egt', date('Y-m-d H:i:s', strtotime(date('Y-m-d')))];
        }
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $where['t1.user_id'] = ['like', '%' . $search_name . '%'];
            $whereOr['t1.to_user'] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::table('blacklist')
            ->alias('t1')
            ->field('t1.*,t2.name,t2.head_portrait')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)
            ->whereOr($whereOr)
            ->order('t1.addtime desc,t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //取消关注
    public function gzdel()
    {
        if (request()->isAjax()) {

            $id = input('id');

            if ($id) {
                $db = Db::name('attention')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    //取消拉黑
    public function lhdel()
    {
        if (request()->isAjax()) {

            $id = input('id');

            if ($id) {
                $db = Db::name('blacklist')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function location()
    {
        $action = input('action');
        $id = input('id/d');

        $this->assign('action', $action);
        $this->assign('id', $id);
        return $this->fetch();
    }

    //照片管理
    public function imglist()
    {
        $where = [];

        $type = input('type');
        if ($type == 1) {
            $where['t1.time'] = ['egt', date('Y-m-d H:i:s', strtotime(date('Y-m-d')))];
        }

        $status = input('status/d');

        if ($status === null) {
            $status = 1;
        }
        $where['t1.status'] = $status;
        $this->assign('status', $status);

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        // $data = Db::name('user_img')->where($where)->order('time desc')->paginate(_getCachePages(),false,['query'=>request()->param()]);


        $data = Db::table('user_img')
            ->alias('t1')
            ->field('t1.*,t2.name, t2.phone')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)
            ->order('time desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //标签列表
    public function tags()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $order = input('order') ? input('order') : 'asc';
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }

        $data = db('tags')->where($where)->order('des ' . $order . ',id ' . $order)->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    //添加标签
    public function tagsadd()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input();

            if (!$id) { //添加数据
                unset($post['url']);
                $res = db('tags')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                unset($post['url']);
                $res = db('tags')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = db('tags')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除标签
    public function tagsDel()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('tags')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // 充值选项
    public function topupcate()
    {
        $data = Db::name('topup_select')->order('sort desc, id asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $nobles = Db::name('grade_noble')->column('id, name');
        $cars = Db::name('car')->where(['is_hidden' => 0])->column('id, name');

        $this->assign('nobles', $nobles);
        $this->assign('cars', $cars);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }

    // 添加/编辑充值选项
    public function topupcateadd()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$id) {//添加数据
                $db = Db::name('topup_select')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {//修改数据
                $db = Db::name('topup_select')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('topup_select')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $nobles = Db::name('grade_noble')->select();
            $cars = Db::name('car')->where(['is_hidden' => 0])->select();

            $this->assign('nobles', $nobles);
            $this->assign('cars', $cars);

            $data = $this->fetch();
        }
        return $data;
    }

    // 删除充值选项
    public function topupcatedel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('topup_select')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * 敏感词列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function mingan()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = db('filter_word')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    //添加标签
    public function minganadd()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('');

            unset($post['url']);

            if (!$id) { //添加数据
                $record_id = Db::name('filter_word')->where(['name' => $post['name']])->value('id');
                if ($record_id) return ['err' => '敏感词已存在'];

                $res = db('filter_word')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                $record_id = Db::name('filter_word')->where(['name' => $post['name']])->value('id');
                if ($record_id != $id) return ['err' => '敏感词已存在'];

                $res = db('filter_word')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = db('filter_word')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除标签
    public function minganDel()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('filter_word')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * 记录用户查看阅读即焚的照片时手机操作截屏照片
     */
    public function screenshotRecord()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            if ($search_type == 'id') {
                $where[$search_type] = $search_name;
            } else {
                $where['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $where['t1.num'] = ['gt', 1];
        $data = Db::name('screenshot_records t1')->field('t1.*, t2.name, t2.phone')->join('user t2', 't2.id = t1.user_id')->where($where)->order('t1.update_time desc, t1.id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function editrecords()
    {

        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if ($id) {  //修改数据
                if (!$post['banned_end_time']) return ['err' => '先选择冻结时间'];

                $data = Db::name('screenshot_records')->where('id', $id)->find();

                Db::name('screenshot_records')->where('id', $id)->setField('status', 1);
                $db = Db::name('user')->where('id', $data['user_id'])->update(['banned_end_time' => $post['banned_end_time'], 'is_banned' => 1]);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('user')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delrecords()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('screenshot_records')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function addimage()
    {
        if (request()->isAjax()) {

            $post = input('');

            if (!isset($post['masterimg']) || !$post['masterimg']) {
                return ['err' => '至少需上传一张图片'];
            }

            if ($post['burn'] == 2) {
                if (!isset($post['packet']) || !$post['packet']) {
                    return ['err' => '输入红包金额'];
                }
                $post['burn'] = 0;
            }

            $post['masterimg'] = explode(',', $post['masterimg']);
            //$post['masterimg'][0] = substr($post['masterimg'][0], 6);

            $con = [];
            foreach ($post['masterimg'] as $k => $v) {
                $con[] = [
                    'user_id' => $post['id'],
                    'pic' => json_encode([$v]),
                    'picthumb' => json_encode([$v]),
                    //'picthumb' => json_encode([substr($v, 0, 15) . 'thumb' . substr($v, 15)]),
                    'burn' => isset($post['burn']) ? $post['burn'] : 0,
                    'packet' => isset($post['packet']) ? $post['packet'] : 0,
                ];
            }

            $result = Db::name('user_img')->insertAll($con);

            if ($result) {
                $data = ['ret' => '添加成功'];
            } else {
                $data = ['err' => '添加失败'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function addvideo()
    {
        if (request()->isAjax()) {

            $post = input('');

            if (!isset($post['cover']) || !$post['cover']) {
                return ['err' => '请先上传封面图'];
            }

            if (!isset($post['pic']) || !$post['pic']) {
                return ['err' => '请先上传视频'];
            }

            if ($post['burn'] == 2) {
                if (!isset($post['packet']) || !$post['packet']) {
                    return ['err' => '输入红包金额'];
                }
                $post['burn'] = 0;
            }

            $con = [
                'user_id' => $post['id'],
                'cover' => $post['cover'],
                'pic' => json_encode([$post['pic']]),
                'picthumb' => '',
                'burn' => isset($post['burn']) ? $post['burn'] : 0,
                'packet' => isset($post['packet']) ? $post['packet'] : 0,
                'types' => 2
            ];

            $result = Db::name('user_img')->insert($con);

            if ($result) {
                $data = ['ret' => '添加成功'];
            } else {
                $data = ['err' => '添加失败'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function all()
    {
        //if (request()->isAjax()) {
        $post = input('')["delAll"];
        //$type = input('type');

        if ($post) {
            //$post = $post['delAll'];

            $result = Db::table('vip_order')
                ->alias('t1')
                ->field('t1.*,t2.name, t3.name, t3.description')
                ->join('user t2', 't2.id = t1.user_id')
                ->join('vip_style t3', 't1.sid = t3.id')
                ->where(['t1.id' => ['in', $post]])
                ->select();

            foreach ($result as $k => $v) {
                if ($v['pay'] == 1) {
                    $result[$k]['pay'] = '微信';
                } else if ($v['pay'] == 2) {
                    $result[$k]['pay'] = '支付宝';
                } else if ($v['pay'] == 3) {
                    $result[$k]['pay'] = '余额';
                }

                if ($v['type'] == 1) {
                    $result[$k]['type'] = '已支付';
                } else {
                    $result[$k]['type'] = '未支付';
                }
            }

            $this->installExcel($result);

            if (1) {
                $data = ['ret' => '成功'];
            } else {
                $data = ['err' => '失败'];
            }
        } else {
            $data = ['err' => '失败，未选中数据'];
        }
        /*} else {
            $data = ['err' => '提交类型错误'];
        }*/
        return $data;
    }

    public function installExcel($data)
    {
        // 从数据库查询需要的数据
        // $data = model('admin/Loginlog')->where($where)->order('id','desc')->select();
        // Create new Spreadsheet object
        $spreadsheet = new Spreadsheet();

        // Add title
        $spreadsheet->setActiveSheetIndex(0)
            ->setCellValue('A1', '订单号')
            ->setCellValue('B1', '用户id')
            ->setCellValue('C1', '用户昵称')
            ->setCellValue('D1', '支付方式')
            ->setCellValue('E1', '支付状态')
            ->setCellValue('F1', '支付详情')
            ->setCellValue('G1', '支付时间')
            ->setCellValue('H1', '备注');
        // Rename worksheet
        $spreadsheet->getActiveSheet()->setTitle('订单情况');
        $i = 2;
        foreach ($data as $v) {
            //$name = isset($rs['name'][$k]) ? $rs['name'][$k] : 'undefined';
            // Add data
            $spreadsheet->getActiveSheet()
                ->setCellValue('A' . $i, $v['vip_order'])
                ->setCellValue('B' . $i, $v['user_id'])
                ->setCellValue('C' . $i, $v['name'])
                ->setCellValue('D' . $i, $v['pay'])
                ->setCellValue('E' . $i, $v['type'])
                ->setCellValue('F' . $i, $v['name'] . ' / ' . $v['price'])
                ->setCellValue('G' . $i, date('Y-m-d H:i',strtotime($v['time'])))
                ->setCellValue('H' . $i, $v['desc']);
            $i++;
        }
        //Set width
        /*$spreadsheet->getActiveSheet()
            ->getColumnDimension('A')
            ->setWidth(15);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('B')
            ->setWidth(15);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('C')
            ->setWidth(60);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('D')
            ->setWidth(15);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('E')
            ->setWidth(20);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('F')
            ->setWidth(20);*/
        // Set alignment
        $spreadsheet->getActiveSheet()->getStyle('A1:F' . $i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $spreadsheet->getActiveSheet()->getStyle('C2:C' . $i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $spreadsheet->setActiveSheetIndex(0);
        ob_clean();
        header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
        header('content-type:application/octet-stream');
        header('Cache-Control: max-age=0');
        header("Content-Type:application/force-download");
        header("Content-Type:application/download");
        //header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . time() . microtime(true) . '.xlsx"');
        //header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);

        $writer->save('php://output');
        exit;
    }

    //账号充值
    public function money()
    {
        $id = input("id");

        if (request()->isAjax()) {

            $post = input('post.');

            if (!input('price')) {
                return ['err' => '充值金额不能为空'];
            }

            switch ($post['gateway']) {
                case 1:
                    $field = 'volley';
                    $state = 0;
                    break;
                case 2:
                    $field = 'score';
                    $state = 1;
                    break;
            }

            if ($post['toward']) {

                if (!input('content')) {
                    $post['content'] = '后台转账';
                }

                $db = Db::name('user')->where('id', $id)->setInc($field, $post['price']);
                Db::name('volley_desc')->insert([
                    'user_id' => $id,
                    'content' => $post['content'],
                    'price' => $post['price'],
                    'types' => 1,
                    'state' => $state,
                    'time' => time()
                ]);

                Db::name('topup')->insert([
                    'fk_userid' => $id,
                    'type' => 3,
                    'state' => 1,
                    'price' => $post['price'],
                    'money' => $post['price'],
                ]);
            } else {

                if (!input('content')) {
                    $post['content'] = '后台转账';
                }

                $db = Db::name('user')->where('id', $id)->setDec($field, $post['price']);
                Db::name('volley_desc')->insert([
                    'user_id' => $id,
                    'content' => $post['content'],
                    'price' => $post['price'],
                    'state' => $state,
                    'time' => time()
                ]);
            }

            if ($db) {
                $admin = session('admin', '', 'mmjtAdmin');
                Db::name('admin_logs')->insert(['admin' => $admin['name'], 'user_id' => $id, 'content' => $post['content']]);

                $data = ['ret' => '成功'];
            } else {
                $data = ['err' => '失败'];
            }

        } else {
            if ($id) {
                $name = Db::name('user')->find($id);
                $this->assign('name', $name);
                $data = $this->fetch();
            } else {
                $data = ['err' => 'id参数错误'];
            }
        }
        return $data;
    }

    public function rengong()
    {
        $state = input('state');

        $map = [];
        $daili = [];    //城市代理管理员查看筛选

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
            $daili['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $daili['state'] = '1';
        //$sum = db('topup')->alias('t1')->join('user t2', 't2.id = t1.fk_userid')->where($daili)->sum('t1.price');
        //$month = db('topup')->alias('t1')->join('user t2', 't2.id = t1.fk_userid')->where($daili)->where('addtime', 'like', date('Y-m') . '%')->sum('t1.price');

        if ($state !== null) {
            $map['t1.state'] = $state;
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $date = input('date');
        if ($date) {
            $map['t1.addtime'] = ['like', '%' . $date . '%'];
        }

        $map['t1.type'] = 3;

        $data = Db::table('topup')
            ->alias('t1')
            ->field('t1.*,t2.name')
            ->join('user t2', 't2.id = t1.fk_userid')
            ->where($map)
            ->order('t1.addtime desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $sum = Db::table('topup t1')->join('user t2', 't2.id = t1.fk_userid')->where($map)->sum('price');

        $this->assign('sum', $sum);
        //$this->assign('month', $month);
        $this->assign('state', $state);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function rengongvip()
    {
        $map = [];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $map['t2.city'] = ['like', $admin['city'] . '%'];
        }

        $type = input('type');

        if ($type == 1) {
            $map['t1.type'] = '0';
        } else if ($type == 2) {
            $map['t1.type'] = '1';
        } else if ($type == 3) {
            $map['t1.pay'] = '1';
        } else if ($type == 4) {
            $map['t1.pay'] = '2';
        } else if ($type == 5) {
            $map['t1.pay'] = '3';
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $map['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $date = input('date');
        if ($date) {
            $map['t1.time'] = ['like', '%' . $date . '%'];
        }

        $map['t1.desc'] = ['like', '%后台添加'];

        $data = Db::table('vip_order')
            ->alias('t1')
            ->field('t1.*,t2.name, t3.name, t3.description')
            ->join('user t2', 't2.id = t1.user_id')
            ->join('vip_style t3', 't1.sid = t3.id')
            ->where($map)
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $sum = Db::table('vip_order t1')->join('user t2', 't2.id = t1.user_id')->where($map)->sum('price');

        $this->assign('sum', $sum);
        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    // =================  2020/10/29  ======================

    public function conditions()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $order = input('order') ? input('order') : 'asc';
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }

        $data = db('user_conditions')->where($where)->order('des ' . $order . ',id ' . $order)->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function addconditions()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) { //添加数据
                unset($post['url']);
                $res = db('user_conditions')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据

                $res = db('user_conditions')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = db('user_conditions')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delconditions()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('user_conditions')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }



    public function yaoqingma()
    {
        $map = [];
        $revideo = input('revideo');

        if ($revideo !== null) {
            $map['type'] = $revideo;
        }
        $this->assign('revideo', $revideo);


        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $map[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('code')->where($map)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function addyaoqingma()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$id) { //添加数据
                if (!$post['uid']) {
                    return ['err' => '用户ID不能为空'];
                }
                $res = Db::name('preach')->where('uid', $post['uid'])->where('state', 'in', '0,1')->select();
                if ($res) {
                    return ['err' => '用户已申请，待审核或已通过'];
                }

                $db = Db::name('preach')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {  //修改数据
                $post['updatetime'] = date('Y-m-d H:i:s');

                $db = Db::name('code')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }

        } else {
            if ($id) {
                $name = Db::name('code')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delyaoqingma()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('code')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function codeinfo()
    {
        $code = input('code');
        if (request()->isAjax()) {
            $data = ['ret' => '修改成功'];
        } else {
            if ($code) {
                $name = Db::name('self_code')->where('code', $code)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function order()
    {
        $where = ['t1.status' => 1];

        $types = input('types');
        if ($types) {
            $where['t1.types'] = $types;
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where['t1.' . $search_type] = $search_name;
        }
    
        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $where['t1.create_time'] = ['between', [strtotime($start), strtotime($end) + 86400]];
        } else if ($start && !$end) {
            $where['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['t1.create_time'] = ['lt', strtotime($start) + 86400];
        }

        $data = Db::name('order_common t1')
            ->field('t1.*, t2.name,t2.phone')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)->order('t1.id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
    
        $sum = Db::name('order_common t1')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)->sum('t1.money');

        $this->assign('sum', $sum);
        $this->assign('types', $types);
    
        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('data', $data);
        $this->assign('page', $data->render());

        return $this->fetch();
    }

    public function delorder()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('order_common')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function balance()
    {
        $where = ['t1.id' => ['gt', 0]];

        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $where['t2.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('volley_desc t1')
            ->field('t1.*,t2.name,t2.phone')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function beauty()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('beauty_image')->where($where)->order('sort desc, id asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function addBeauty()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) {

                $res = Db::name('beauty_image')->insert($post);
                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $res = Db::name('beauty_image')->where('id', $id)->update($post);
                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }

        } else {
            if ($id) {
                $name = Db::name('beauty_image')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }

        return $data;
    }

    public function delBeauty()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('beauty_image')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function tongji()
    {
        $data = Db::name('tongji_user')->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function tongjiProxy()
    {
        $date = input('date');

        $data = Db::name('tongji_proxy t1')
            ->field('t1.*, t2.name, t2.phone')
            ->join('user t2', 't2.id = t1.user_id')
            ->where(['t1.date' => $date])
            ->order('t1.id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function chat()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $types = input('types');
        if ($types) {
            $where['types'] = $types;
        }

        $data = Db::name('config_price')->where($where)->order('id asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('types', $types);

        return $this->fetch();
    }

    public function addChat()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) {

                $res = Db::name('config_price')->insert($post);
                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $res = Db::name('config_price')->where('id', $id)->update($post);
                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }

        } else {
            if ($id) {
                $name = Db::name('config_price')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }

        return $data;
    }

    public function delChat()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('config_price')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function certification()
    {
        $where = [];

        $types = input('types') ?: 1;
        if ($types) {
            $where['t1.types'] = $types;
        }

        $status = input('status');
        if ($status !== null) {
            $where['t1.status'] = $status;
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where['t2.' . $search_type] = $search_name;
        }

        $data = Db::name('user_certification t1')
            ->field('t1.*, t2.name,t2.phone')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($where)->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('types', $types);
        $this->assign('status', $status);

        return $this->fetch();
    }

    public function certificationWatch($id)
    {
        $name = Db::name('user_certification')->find($id);

        if ($name && $name['images']) {
            $name['images'] = explode(',', $name['images']);
        }

        $this->assign('name', $name);
        return $this->fetch();
    }

    public function certificationEdit()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if ($id) {
                $certification = Db::name('user_certification')->find($id);

                if ($post['status'] == -1) {
                    $status = 3;
                } else if ($post['status'] == 0) {
                    $status = 1;
                } else if ($post['status'] == 1) {
                    $status = 2;
                }

                $contain = ['', 'realname_auth', 'is_education_authentication', 'car_auth', 'house_auth', 'voice_auth'];
                $msg = ['', '实名认证', '学历认证', '车辆认证', '房产认证', '语音签名'];
                $types = [1 => 'name_auth', 2 => 'education_auth', 3 => 'car_auth', 4 => 'house_auth', 5 => 'voice'];

                $where = [$contain[$certification['types']] => $status];

                Db::name('user')->where(['id' => $certification['user_id']])->update($where);

                $result = Db::name('user_certification')->where('id', $id)->update(['status' => $post['status'], 'reason' => input('reason'), 'update_time' => time()]);


                if (in_array($post['status'], [-1,1])) {
                    if ($post['status'] == -1) {
                        $content = $msg[$certification['types']] . '未通过，请重新提交。原因:' . input('reason');
                    } else {
                        if ($certification['types'] == 5) {
                            Db::name('user')->where(['id' => $certification['user_id']])->update(['voice' => $certification['image_front']]);
                        }

                        $content = '你的'.$msg[$certification['types']] . '已通过。';

                        // 任务
                        Task::finish($types[$certification['types']], $certification['user_id']);
                    }

                    Privatechat::notice($certification['user_id'], $content);
                }

                $data = $result ? ['ret' => '修改成功'] : ['err' => '修改失败'];
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }

    public function certificationDel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('user_certification')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function authadd()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            
            $post = input('post.');
            
            if ($id) {
                $photo = Db::name('user_img')->find($id);
                
                if ($photo) {
                    $contain = ['status' => $post['shenhe']];
    
                    if ($photo['types'] == 1 && $photo['burn'] == 0 && $photo['packet'] == 0 && $post['shenhe'] == 1) {
                        $image = json_decode($photo['pic'], true)[0];
                        
                        $where = ['type' => 4, 'userid' => $photo['user_id']];
                        if ($photo['join_dynamic']) {
                            $where['dy_id'] = $photo['join_dynamic'];
                        } else {
                            $similar = Db::name('user_img')->where([
                                'types' => 1,
                                'user_id' => $photo['user_id'],
                                'burn' => 0,
                                'packet' => 0,
                                'status' => 1,
                                'remark' => $photo['remark']
                            ])->find($id);
                            
                            if ($similar && $similar['join_dynamic']) {
                                $where['dy_id'] = $similar['join_dynamic'];
                            }
                        }
                        $dynamic = Db::name('dymanic')->where($where)->find();
                        
                        if (isset($where['dy_id']) && $dynamic) {
                            $sumbImage = $dynamic['sumbImage'] . ',' . $image;
                            $masterimg = $dynamic['masterimg'] . ',' . $image;
    
                            Db::name('dymanic')->where(['dy_id' => $dynamic['dy_id']])->update(['sumbImage' => $sumbImage, 'masterimg' => $masterimg]);
                        } else {
                            $city = Db::name('user')->where(['id' => $photo['user_id']])->value('city');
    
                            $dynamic_id = Db::name('dymanic')->insertGetId([
                                'type' => 4,
                                'userid' => $photo['user_id'],
                                'sumbImage' => $image,
                                'masterimg' => $image,
                                'citys' => $city ?: '',
                                'shenhe_time' => time(),
                            ]);
    
                            $contain['join_dynamic'] = $dynamic_id;
                        }
                    }
    
                    $db = Db::name('user_img')->where('id', $id)->update($contain);
                } else {
                    return ['err' => '照片不存在'];
                }
                
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }

    public function detail()
    {
        $id = input("id");

        if (request()->isAjax()) {

        } else {
            if ($id) {
                $name = Db::name('withdraw')->find($id);

                if ($name) {
                    $name['data'] = json_decode($name['data'], true);

                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }

        return $data;
    }

    public function exchange()
    {
        $data = Db::name('exchange_style')->order('sort desc, id asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function addExchange()
    {

        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$id) {
                $db = Db::name('exchange_style')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $db = Db::name('exchange_style')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('exchange_style')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delExchange()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('exchange_style')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function exportData()
    {
        $post = input('')['delAll'];
        $sex = input('sex');

        if ($post || $sex) {

            if ($sex) {
                $sex = $sex == 1 ? '男' : '女';
                
                $result = Db::name('user')->field('id, name, phone')->where(['sex' => $sex])->select();
            } else {
                $result = Db::name('user')->field('id, name, phone')->where(['id' => ['in', $post]])->select();
            }

            if ($result) {
                $this->installUsers($result);
            }

            $data = ['ret' => '成功'];
        } else {
            $data = ['err' => '失败，未选中数据'];
        }
        return $data;
    }

    public function installUsers($data)
    {
        $spreadsheet = new Spreadsheet();

        // Add title
        /*$spreadsheet->setActiveSheetIndex(0)
            ->setCellValue('A1', 'ID')
            ->setCellValue('B1', '昵称')
            ->setCellValue('C1', '手机');*/

        // Rename worksheet
        $spreadsheet->getActiveSheet()->setTitle('用户');
        $i = 1;
        foreach ($data as $v) {
            // Add data
            $spreadsheet->getActiveSheet()
                ->setCellValue('A' . $i, $v['phone'] . "\t");
            $i++;
        }

        // Set alignment
        $spreadsheet->getActiveSheet()->getStyle('A1:F' . $i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $spreadsheet->getActiveSheet()->getStyle('C2:C' . $i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $spreadsheet->setActiveSheetIndex(0);

        ob_clean();
        header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
        header('content-type:application/octet-stream');
        header('Cache-Control: max-age=0');
        header("Content-Type:application/force-download");
        header("Content-Type:application/download");
        header('Content-Disposition: attachment;filename="' . time() . microtime(true) . '.xlsx"');

        $writer = new Xlsx($spreadsheet);

        $writer->save('php://output');

        exit;
    }
    
    // public function inviteCode($id, $yqr)
    // {
    //     $user = Db::name('user')->find($id);
    
    //     if (!$user) {
    //         return ['err' => '用户不存在'];
    //     }
    
    //     $parent = Db::name('user')->where(['id' => ['neq', $id], 'yqm' => $yqr])->find();
    
    //     if (!$parent) {
    //         return ['err' => '邀请码不存在'];
    //     }
        
    //     if ($parent['yqr'] == $user['yqm']) {
    //         return ['err' => '不能绑定下级'];
    //     }
    
    //     Db::name('user')->where(['id' => $id])->setField('yqr', $yqr);
    
    //     return ['err' => '绑定成功'];
    // }
}
